<template>
  <div class="app-container">
    <!-- 对话框(添加 / 修改) -->
    <el-dialog :title="dialogTitle" :visible.sync="dialogVisible" width="45%" v-dialogDrag append-to-body>
      <el-form ref="formRef" :model="formData" :rules="formRules" v-loading="formLoading" label-width="100px">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="名称" prop="modelName">
              <el-input v-model="formData.modelName" placeholder="请输入名称"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="定额" prop="fixed">
              <el-input v-model="formData.fixed" placeholder="请输入定额"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="IE用户" prop="ieId">
              <el-select
                v-model="formData.ieId"
                placeholder="请选择IE用户"
                filterable
                clearable
                remote
                :remote-method="remoteUserSearch"
                :loading="userLoading"
                style="width: 100%"
                @change="handleUserSelect('ie', $event)"
              >
                <el-option v-for="user in userList" :key="user.id" :label="user.nickname" :value="user.id"/>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="PE用户" prop="peId">
              <el-select
                v-model="formData.peId"
                placeholder="请选择PE用户"
                filterable clearable
                remote
                :remote-method="remoteUserSearch"
                :loading="userLoading"
                style="width: 100%"
                @change="handleUserSelect('pe', $event)"
              >
                <el-option v-for="user in userList" :key="user.id" :label="user.nickname" :value="user.id"/>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="QE用户" prop="qeId">
              <el-select
                v-model="formData.qeId"
                placeholder="请选择QE用户"
                filterable clearable
                remote
                :remote-method="remoteUserSearch"
                :loading="userLoading"
                style="width: 100%"
                @change="handleUserSelect('qe', $event)"
              >
                <el-option v-for="user in userList" :key="user.id" :label="user.nickname" :value="user.id"/>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="ME用户" prop="meId">
              <el-select
                v-model="formData.meId"
                placeholder="请选择ME用户"
                filterable clearable
                remote
                :remote-method="remoteUserSearch"
                :loading="userLoading"
                style="width: 100%"
                @change="handleUserSelect('me', $event)"
              >
                <el-option v-for="user in userList" :key="user.id" :label="user.nickname" :value="user.id"/>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="节拍" prop="beat">
              <el-input v-model="formData.beat" placeholder="请输入节拍"/>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="备注" prop="remark">
              <el-input v-model="formData.remark" placeholder="请输入备注" type="textarea" :rows="3"/>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm" :disabled="formLoading">确 定</el-button>
        <el-button @click="dialogVisible = false">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import * as ModelInfoApi from '@/api/lamp/modelinfo';
import {
  listUser,
} from "@/api/system/user";

export default {
  name: "ModelInfoForm",
  components: {},
  data() {
    return {
      userList:[],
      userLoading: false,
      // 弹出层标题
      dialogTitle: "",
      // 是否显示弹出层
      dialogVisible: false,
      // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
      formLoading: false,
      // 表单参数
      formData: {
        id: undefined,
        modelName: undefined,
        fixed: undefined,
        ieId: undefined,
        ieName: undefined,
        peId: undefined,
        peName: undefined,
        qeId: undefined,
        qeName: undefined,
        meId: undefined,
        meName: undefined,
        beat: undefined,
        remark: undefined,
      },
      // 表单校验
      formRules: {
        modelName: [{required: true, message: '名称不能为空', trigger: 'blur'}],
        fixed: [{required: true, message: '定额不能为空', trigger: 'blur'}],
        ieId: [{required: true, message: 'IE用户不能为空', trigger: 'blur'}],
        peId: [{required: true, message: 'PE用户不能为空', trigger: 'blur'}],
        qeId: [{required: true, message: 'QE用户不能为空', trigger: 'blur'}],
        meId: [{required: true, message: 'ME用户不能为空', trigger: 'blur'}],
        beat: [{required: true, message: '节拍不能为空', trigger: 'blur'}],
      },
    };
  },
  created() {
    this.loadUserList();
  },
  methods: {
    // 加载用户列表
    loadUserList() {
      listUser({
        pageNo: 1,
        pageSize: 20,
      }).then(res => {
        this.userList = res.data.list;
      });
    },

    // 远端搜索用户
    remoteUserSearch(keyword) {
      if (!keyword) {
        this.loadUserList();
        return;
      }

      this.userLoading = true;
      listUser({
        pageNo: 1,
        pageSize: 20,
        nickname: keyword
      }).then(res => {
        this.userList = res.data.list;
        this.userLoading = false;
      }).catch(() => {
        this.userLoading = false;
      });
    },

    // 处理用户选择
    handleUserSelect(type, id) {
      const selectedUser = this.userList.find(user => user.id === id);
      if (selectedUser) {
        this.formData[`${type}Name`] = selectedUser.nickname;
      }
    },

    /** 打开弹窗 */
    async open(id) {
      this.dialogVisible = true;
      this.reset();
      // 修改时，设置数据
      if (id) {
        this.dialogTitle = "编辑机种信息";
        this.formLoading = true;
        try {
          const res = await ModelInfoApi.getModelInfo(id);
          this.formData = res.data;
        } finally {
          this.formLoading = false;
        }
      } else {
        this.dialogTitle = "新增机种信息";
      }
    },
    /** 提交按钮 */
    async submitForm() {
      // 校验主表
      await this.$refs["formRef"].validate();
      this.formLoading = true;
      try {
        const data = this.formData;
        // 修改的提交
        if (data.id) {
          await ModelInfoApi.updateModelInfo(data);
          this.$modal.msgSuccess("修改成功");
          this.dialogVisible = false;
          this.$emit('success');
          return;
        }
        // 添加的提交
        await ModelInfoApi.createModelInfo(data);
        this.$modal.msgSuccess("新增成功");
        this.dialogVisible = false;
        this.$emit('success');
      } finally {
        this.formLoading = false;
      }
    },
    /** 表单重置 */
    reset() {
      this.formData = {
        id: undefined,
        modelName: undefined,
        fixed: undefined,
        ieId: undefined,
        ieName: undefined,
        peId: undefined,
        peName: undefined,
        qeId: undefined,
        qeName: undefined,
        meId: undefined,
        meName: undefined,
        beat: undefined,
        remark: undefined,
      };
      this.resetForm("formRef");
    }
  }
};
</script>
<style scoped>
.el-select {
  width: 100%;
}

/* 调整表单布局样式 */
.el-form-item {
  margin-bottom: 18px;
}

/* 备注输入框样式优化 */
.el-textarea__inner {
  resize: vertical;
}
</style>
